<?php
namespace App\Http\Controllers\Api;

use App\Library\FileManager as FileManager;
use App\Library\OSS;
use App\Modules\Common\Models\PageConfig;
use App\Modules\Shop\Models\Banner;
use App\Modules\Shop\Models\Category;
use App\Modules\System\Recommend;
use App\Modules\System\RuleIntroduce;
use Carbon\Carbon;
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;
use App\Modules\System\Models\Brand;

class CommonController extends ApiController
{
    public function upload(Application $application, Request $request)
    {
        $this->validate($request, [
            'image' => 'required|file|mimetypes:image/jpeg,image/png,image/gif',
            'type'  => 'required|string',
        ]);

        $file = $request->file('image');
        $type = $request->input('type');

        $key = $type."/".Carbon::now()->timestamp."/".uniqid().$file->getExtension();
        /** @var OSS $oss */
        $oss = OSS::instance();
        $oss->storeFile($key, $file->getRealPath());
        return $this->success([
            'key' => $key,
            'url' => $oss->getUrl($key),
        ]);
    }

    public function getUpLoadConfig(Request $request)
    {
        $this->validate($request, [
            'type' => 'required|string',
            'ext' => 'required|string',
        ]);

        $type = $request->input('type');
        $ext = $request->input('ext');

        $date = now()->toDateString();
        $time = now()->format('His');
        $rand = Str::random(6);

        $key = "{$type}/{$date}/{$time}-{$rand}.{$ext}";
        $config = OSS::instance()->getSign($key);

        return $this->success($config);
    }

    public function encryptor(Request $request)
    {
        $user = $this->getUser();
        $iv = $request->input('iv');
        $encryptData = $request->input('encrypted_data');
        $app = EasyWeChat::miniProgram();
        try {
            $decryptedData = $app->encryptor->decryptData($user->session_key, $iv, $encryptData);
        } catch (\Throwable $e) {
            return $this->fail('session_key过期', 1001);
        }

        return $this->success($decryptedData);
    }

    public function getBanner()
    {
        $banner = Banner::query()
            ->where('type', Banner::TYPE_PLATFORM)
            ->get()
            ->map(function ($item) {
                $item->image = OSS::instance()->getUrl($item->image);
                return $item;
            });
        return $this->success($banner);
    }
//    public function getCategory()
//    {
//        $category = Category::query()
//            ->get();
//        return $this->success($category);
//    }

    public function getRecommend()
    {
        $recommend = Recommend::query()->get()
            ->map(function ($item) {
                $item->image = OSS::instance()->getUrl($item->image);
                return $item;
            });

        return $this->success($recommend);
    }

    public function getPageConfig()
    {
        $page = PageConfig::query()->first();
        if (!is_null($page)) {
            $page->customer_service_qr_code = empty($page->customer_service_qr_code) ? null : OSS::instance()->getUrl($page->customer_service_qr_code);
            $page->partner_bg = empty($page->customer_service_qr_code) ? null : OSS::instance()->getUrl($page->partner_bg);
            $page->share_image = empty($page->share_image)? null : OSS::instance()->getUrl($page->share_image);
            $rule = [];
            if (!empty($page->customer_service_qr_code)) {
                foreach ($page->rule_image as $item) {
                    $rule[] = OSS::instance()->getUrl($item);
                }
            }
            $page->rule_image = $rule;
        }
        return $this->success($page);
    }

    public function getRebateRule(Request $request)
    {
        $this->validate($request, [
            'offset' => 'nullable|integer',
            'count' => 'nullable|integer',
        ]);
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 10);
        $re = RuleIntroduce::query()
            ->orderBy('sort', 'desc')
            ->orderBy('created_at', 'desc')
            ->offset($offset)
            ->limit($count)
            ->get()
            ->map(function ($item) {
                return [
                    'image' =>  OSS::instance()->getUrl($item->image),
                    'sort' => $item->sort,
                ];
            });
        return $this->success($re);
    }

    /**
     * 查询首页分类
     */
    public function getCategory(Request $request)
    {
        $this->validate($request, [
            'pid'          => 'integer',//父级id
            'is_view_show' => 'integer',//是否前台显示1是0否
        ]);

        $pid          = $request->input('pid', 0);
        $is_view_show = $request->input('is_view_show', 1);
        $re = Category::query()
            // ->when(!empty($pid), function ($query) use ($brand_id) {
            //     return $re->where('pid', $pid);
            // })
            ->where('pid', $pid)
            ->where('is_view_show', $is_view_show)
            ->orderBy('sort', 'desc')
            ->get()
            ->map(function ($item) {
                return [
                    'id'   => $item->id,
                    'name' => $item->name,
                ];
            });
        return $this->success($re);
    }

    /**
     * 查询分类
     */
    public function queryCategory(Request $request)
    {
        $this->validate($request, [
            'top_category_id'   => 'integer',
            'first_category_id' => 'integer',
        ]);

        $top_category_id   = $request->input('top_category_id', '');
        $first_category_id = $request->input('first_category_id', '');

        $query = Category::query()
                ->orderBy('sort', 'desc');

        if ($top_category_id != '') {
            $query->where('top_category_id', $top_category_id);
        }

        if ($first_category_id != '') {
            $query->where('first_category_id', $first_category_id);
        }

        $re = $query->get()
                    ->map(function ($item) {
                        return [
                            'id'   => $item->id,
                            'name' => $item->name,
                        ];
                    });
        return $this->success($re);
    }

    /**
     * 获取筛选参数
     */
    public function queryParams(Request $request){
        
        $this->validate($request, [
            'top_category_id' => 'integer',
        ]);

        $top_category_id   = $request->input('top_category_id', '');

        $aParams = [];
        if (empty($top_category_id)) {
            return $this->success($aParams);
        }

        $topCategory = Category::query()->where('id', $top_category_id)->first('name');
        $topCategory = [$topCategory->name];
        $topCategoryId = [$top_category_id];
        $categoryData = Category::query()
                        ->where('deleted_at', null)
                        ->where('top_category_id', $topCategoryId)
                        ->get(['id','name', 'first_category_id', 'top_category_id'])->toArray();

        $aSpec = [];
        if (!empty($topCategoryId)) {
            foreach ($topCategoryId as $k => $v) {
               $tmp = [];
                foreach ($categoryData as $k1 => $v1) {
                    if ($v1['first_category_id'] != 0) {
                        $aSpec['title'] = '规格与功能';
                        $aSpec['field'] = 'category_id';
                        $v1['flag'] = '';
                        $aSpec['data'][$v1['name']] = $v1;
                    }
                    if ($v1['top_category_id'] == $v && $v1['first_category_id'] == 0) {
                        $tmp['title'] = $topCategory[$k];
                        $tmp['field'] = 'first_category_id';
                        // $tmp['data'][] = $v1;
                        $tmp['data'][$v1['name']] = $v1;
                    }
                }

                $aParams[] = $tmp;
            }
        }
        $aParams[] = $aSpec;
        
        //获取品牌
        $brand = Brand::query()->where('parent', $topCategory)->get(['id','name'])->toArray();
        $brandData = [];
        if (!empty($brand)) {
            foreach ($brand as $key => $value) {
                $brandData[$value['name']] = [
                    'id'     => $value['id'],
                    'name'   => $value['name'],
                ];
            }
        }

        $aParams[] = [
            'title' => '品牌',
            'field' => 'brand_id',
            'data'  => $brandData,
        ];
        
        return $this->success($aParams);
    }
}
